package logic

import (
	"Junior_two/video/videoapi/internal/utils"
	"Junior_two/video/videorpc/pb/videoRpc"
	"context"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/validation"
	"github.com/dgrijalva/jwt-go/v4"
	"net/http"
	"strconv"
	"time"

	"Junior_two/video/videoapi/internal/svc"
	"Junior_two/video/videoapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.Loginrequest) (resp *types.Loginresponse, err error) {
	// todo: add your logic here and delete this line
	fmt.Println("====================================")
	valid := validation.Validation{}
	valid.Required(req.Username, "username").Message("username is required")
	valid.Required(req.Password, "password").Message("password is required")
	for _, v := range valid.Errors {
		return &types.Loginresponse{
			Msg:  v.Message,
			Code: http.StatusAccepted,
			Data: "",
		}, nil
	}

	res, err := l.svcCtx.VideoServer.UserLogin(l.ctx, &videoRpc.LoginRequest{
		Username: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return &types.Loginresponse{
			Msg:  err.Error(),
			Code: http.StatusAccepted,
			Data: "",
		}, nil
	}
	if res.Code != http.StatusOK {
		return &types.Loginresponse{
			Msg:  res.Msg,
			Code: res.Code,
			Data: res.Data,
		}, nil
	}
	var m map[string]string
	json.Unmarshal([]byte(res.Data), &m)
	fmt.Println(m)
	resd, _ := strconv.Atoi(m["Id"])
	//登陆成功 生成token
	token := utils.CreateJwt([]byte(l.svcCtx.Config.Auth.AccessSecret), &utils.MyCustomClaims{
		UserId:   int64(resd),
		Username: m["Username"],
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire)),
		},
	})
	logs.Info(token)
	return &types.Loginresponse{
		Msg:  res.Msg,
		Code: res.Code,
		Data: token + "====" + res.Data,
	}, nil
}
